using AntdUI;
using BusinessService.Plugin.DataSource.Sqlite;
using BusinessService.Plugin.DataSource.Sqlite.Dtos;
using BusinessService.Plugin.Entity;
using BusinessService.Plugin.Helper;
using BusinessService.Plugin.ProtocolMethod;
using BusinessService.Plugin.Services;
using BusinessService.Plugin.Services.Dtos;
using EMSSevice;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using System;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using TouchSocket.Sockets;
using WindowsForm;
using WindowsForm.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace winform分层框架
{
    public partial class MainForm : Form
    {
        private BackService _backService => Program.IOC.GetRequiredService<BackService>();
        private TransferDtos _backDtos => Program.IOC.GetRequiredService<TransferDtos>();
        private SqliteLibrary _repSqlite => Program.IOC.GetRequiredService<SqliteLibrary>();
        public MainForm()
        {  //登录窗体
            //UILoginForm frm = new UILoginForm();
            //frm.ShowInTaskbar = true;
            //frm.AutoScaleMode = AutoScaleMode.Font;
            //frm.Width = 1000;
            //frm.Height = 1000;
            //frm.Text = "Login";
            //frm.Title = "请 您 登 录";
            //frm.SubText = "德 尔 智 慧 科 技";
            //frm.OnLogin += Frm_OnLogin;

            //frm.ButtonCancelClick += (object? sender, EventArgs e) => { 
                
            //    frm.Close();

            //    frm.Dispose();
            //    //关闭当前实例    
            //    System.Diagnostics.Process.GetCurrentProcess().Kill();
            //    Application.Exit();//退出当前项目，如果是子项目，则不会停止主项目
            //    System.Environment.Exit(0);//停止所有项目
            //};

            //frm.LoginImage = UILoginForm.UILoginImage.Login4;
            //frm.ShowDialog();
            //if (!frm.IsLogin)
            //{
            //    return;
            //}
            //frm.Dispose();


            InitializeComponent();


        }

        private bool Frm_OnLogin(string userName, string password)
        {
            return userName == "admin" && password == "admin";
        }

        private async void Form1_LoadAsync(object sender, EventArgs e)
        {
            TransferDtos.AutoSend = Settings1.Default.SendAuto;
            TransferDtos.SendCycle = Settings1.Default.SendCycle;
            _repSqlite.CreateSqlite();

            _repSqlite.ErrorEvent += e => { MessageBox.Show(e, "警告"); };

            await Task.Factory.StartNew(() =>
               {
                   Connection();//连接数据源
                   PostAsync();//循环发送消息
               }, TaskCreationOptions.LongRunning);


        }

        /// <summary>
        /// 循环发送数据-任务
        /// </summary>
        /// <returns></returns>
        public async void PostAsync()
        {
            while (true)
            {
                try
                {
                    int cycle = (TransferDtos.SendCycle * 1000);
                    if (cycle <= 0) cycle = 1000;
                    await Task.Delay(cycle);//发送间隔
                    if (TransferDtos.AutoSend)//是否自动发送
                    {
                        await _backService.PostDataAsync();
                    }

                }
                catch (Exception)
                {

                    throw;
                }

            }
        }

        /// <summary>
        /// 连接数据源
        /// </summary>
        public void Connection()
        {
            var param = _repSqlite.AllSetQuery(new AllSetQueryInput());//查询所有的设置参数
            var revList = param.Where(x => x.N_Role == 1).ToList();//接收数据端通讯上下文配置集合
            var sendList = param.Where(x => x.N_Role == 2).ToList();//发送数据端通讯上下文配置集合
            revList.ForEach(async x =>
            {
                ProtocolClass pc = new();
                switch (x.V_ProtocolType)//判断协议类型
                {

                    case "Socket":
                        if (x.TCP_Role.Equals("客户端"))
                        {
                            ProtocolClass.RevContexts.Add(pc.CreatTCPClient(x.V_Name, x.IP, x.Port));
                        };
                        if (x.TCP_Role.Equals("服务器"))
                        {
                            ProtocolClass.RevContexts.Add(pc.CreatTCPServer(x.V_Name, x.IP, x.Port));
                        };
                        break;

                    case "MQTT":
                        ProtocolClass.RevContexts.Add(await pc.CreateMqttObject(x.V_Name, x.IP, x.Port, x.MQTT_UserName, x.MQTT_PassWord, x.MQTT_Topics));
                        break;

                    case "Http":
                        // ProtocolClass.RevContexts.Add(ProtocolClass.CreateMqttObject(x.V_Name, x.IP, x.Port, x.MQTT_UserName, x.MQTT_PassWord));
                        break;

                    default:
                        break;
                }
            });


            sendList.ForEach(async x =>
            {
                ProtocolClass pc = new();
                switch (x.V_ProtocolType)//判断协议类型
                {

                    case "Socket":
                        if (x.TCP_Role.Equals("客户端"))
                        {
                            ProtocolClass.SendContexts.Add(pc.CreatTCPClient(x.V_Name, x.IP, x.Port));
                        };
                        if (x.TCP_Role.Equals("服务器"))
                        {
                            ProtocolClass.SendContexts.Add(pc.CreatTCPServer(x.V_Name, x.IP, x.Port));
                        };
                        break;

                    case "MQTT":
                        ProtocolClass.SendContexts.Add(await pc.CreateMqttObject(x.V_Name, x.IP, x.Port, x.MQTT_UserName, x.MQTT_PassWord, x.MQTT_Topics));
                        break;

                    case "Http":
                        //ProtocolClass.RevContexts.Add(ProtocolClass.CreateMqttObject(x.V_Name, x.IP, x.Port, x.MQTT_UserName, x.MQTT_PassWord));
                        break;

                    default:
                        break;
                }
            });

        }
        Dictionary<string, CancellationTokenSource> _dic = new();
        private async void menu1_SelectChanged(object sender, MenuItem item)
        {

            //await     _backService.PostDataAsync();

            panel1.Controls.Clear();
            switch (item.Text)
            {
                case "监视器": panel1.Controls.Add(FormManage<MonitorForm>.Instance); break;
                case "数据连接设置": panel1.Controls.Add(FormManage<DBConnection>.Instance); break;
                case "数据源设置": panel1.Controls.Add(FormManage<DataSetting>.Instance); break;
                case "发送关系设置": panel1.Controls.Add(FormManage<JsonBuild>.Instance); break;
                case "终端连接设置": panel1.Controls.Add(FormManage<TerminalSet>.Instance); break;
                default: break;
            }
        }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }
    }


    #region  窗体泛型类(单例模式)
    /// <summary>
    /// 窗体泛型类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class FormManage<T> where T : class, new()
    {
        public static T? _instance = null;
        /// <summary>
        /// 单例窗体
        /// </summary>
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {

                    _instance = new T();
                }
                return _instance;
            }
        }
    }

    #endregion



}



